package com.estate.framework.web.service.data;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.estate.common.core.domain.model.ApiResponse;
import com.estate.common.core.domain.model.agent.AgentResp;
import com.estate.common.utils.SnowflakeIdWorker;
import com.estate.framework.web.pojo.ListingFilter;
import com.estate.system.domain.Agent;
import com.estate.system.service.impl.DataAgentsServiceImpl;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class ZenuAgentsApi {

    private static final Logger log = LoggerFactory.getLogger(ZenuAgentsApi.class);

    @Resource
    private DataAgentsServiceImpl dataAgentsServiceImpl;

    @Resource
    public ZenuApiClient client;


    /**
     * 批量保存询盘数据（增量同步，基于时间范围）
     */
    public void saveBatchAgents() {
//        log.info("开始保Agent数据");
        Integer count = countNewAgents();
        // 同步数据记录
        client.syncDataRecord(count, "Agent", "success", "Agent Data", "");
        int pages = 0;
        if (count > 0) {
            pages = count % 10 == 0 ? count / 10 : count / 10 + 1;
            if (pages > 20) {
                pages = 20;
            }
        }
        for (int i = 0; i < pages; i++) {
            Map<String, String> filters = getListingFilter();
            List<Agent> clients = pageAgentsInfo(filters, i + 1, 10);
            dataAgentsServiceImpl.saveBatch(clients);
        }
//        log.info("保存Agent数据结束");
    }


    private Integer countNewAgents() {
        try {
            Map<String, String> filters = getListingFilter();
            ApiResponse<List<AgentResp>> response = client.getAgents(1, 1, filters);
            Long count = response.getPagination().getTotalRecords();
            //将count转为Integer
            return count.intValue();
        } catch (IOException e) {
            log.error("API调用失败: " + e.getMessage());
            // 同步数据记录
            client.syncDataRecord(0, "Agent", "failed", "Agent Data", e.getMessage());
        }
        return 0;
    }

    @NotNull
    private static Map<String, String> getListingFilter() {
        // 获取悉尼时区
        ZoneId sydneyZone = ZoneId.of("Australia/Sydney");

        // 获取悉尼当前日期和昨天的日期
        LocalDate sydneyToday = LocalDate.now(sydneyZone);
        LocalDate sydneyYesterday = sydneyToday.minusDays(1);

        // 设置开始时间为悉尼昨天00:00:00
        String startTime = sydneyYesterday.atStartOfDay(sydneyZone).format(DateTimeFormatter.ISO_DATE_TIME);

        // 设置结束时间为悉尼今天23:59:59
        String endTime = sydneyToday.atTime(23, 59, 59).atZone(sydneyZone).format(DateTimeFormatter.ISO_DATE_TIME);

        ListingFilter filters = new ListingFilter();
        filters.setUpdatedDateFrom(startTime);
        filters.setUpdatedDateTo(endTime);
        Map<String, String> filtersMap = new HashMap<>();

        //将filter转为Map<String, String>
        filtersMap.putAll(filters.toMap());

        return filtersMap;
    }


    /**
     * 带过滤条件Agent的列表
     *
     * @param filters    过滤条件
     * @param pageNumber 页码
     * @param pageSize   每页大小
     * @return Agent列表
     */
    public List<Agent> pageAgentsInfo(Map<String, String> filters, Integer pageNumber, Integer pageSize) {

        try {
            ApiResponse<List<AgentResp>> filteredResponse = client.getAgents(pageNumber, pageSize, filters);

            if (filteredResponse.getSuccess()) {
//                log.info("========>询盘请求成功!总记录数: {};总页数: {};当前页: {};每页大小: {}",
//                        filteredResponse.getPagination().getTotalRecords(),
//                        filteredResponse.getPagination().getTotalPages(),
//                        filteredResponse.getPagination().getPageNumber(),
//                        filteredResponse.getPagination().getPageSize());

                List<AgentResp> filteredData = filteredResponse.getData();

                // 获取所有的询盘ID
                List<Integer> ids = filteredData.stream().map(AgentResp::getId).collect(Collectors.toList());

                // 查询数据库是否已存在
                QueryWrapper<Agent> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().in(Agent::getAgentId, ids);
                List<Agent> existAgents = dataAgentsServiceImpl.list(queryWrapper);

                if (!existAgents.isEmpty()) {
//                    log.info("========>数据库已存在{}条Agent数据,跳过", existAgents.size());
                    List<Integer> existIds = existAgents.stream().map(Agent::getAgentId).collect(Collectors.toList());
                    dataAgentsServiceImpl.remove(queryWrapper);
                    // 去除已存在的数据
//                    filteredData = filteredData.stream()
//                            .filter(enquiryResp -> !existIds.contains(enquiryResp.getId()))
//                            .collect(Collectors.toList());
                }

                List<Agent> agents = new ArrayList<>();

                for (AgentResp agentResp : filteredData) {
                    Agent agent = new Agent();
                    agent.setId(SnowflakeIdWorker.getSingleton().nextId());
                    agent.setAgentId(agentResp.getId());
                    agent.setFirstname(agentResp.getFirstname());
                    agent.setLastname(agentResp.getLastname());
                    agent.setName(agentResp.getName());
                    agent.setEmail(agentResp.getEmail());
                    agent.setMobile(agentResp.getMobile());
                    agent.setPhone(agentResp.getPhone());
                    agent.setPosition(agentResp.getPosition());
                    agent.setRole(agentResp.getRole());
                    agent.setProfile(agentResp.getProfile());
                    agent.setAchievements(agentResp.getAchievements());
                    agent.setStatus(agentResp.getStatus());
                    agent.setIsHidden(agentResp.getIsHidden());
                    agent.setSequence(agentResp.getSequence());
                    agent.setImageUrl(agentResp.getImageUrl());
                    agent.setImageUrlOriginal(agentResp.getImageUrlOriginal());
                    agent.setImageLargeUrl(agentResp.getImageLargeUrl());
                    agent.setImageLargeUrlOriginal(agentResp.getImageLargeUrlOriginal());
                    agent.setVideo(agentResp.getVideo());
                    if (agentResp.getSocialLinks() != null) {
                        agent.setSocialLinks(JSONObject.toJSONString(agentResp.getSocialLinks()));
                    }
                    if (agentResp.getSpecialtySuburbs() != null) {
                        agent.setSpecialtySuburbs(JSONObject.toJSONString(agentResp.getSpecialtySuburbs()));
                    }
                    if (agentResp.getOffices() != null) {
                        agent.setOffices(JSONObject.toJSONString(agentResp.getOffices()));
                    }
                    agent.setCreatedAt(new Date());
                    agent.setUpdatedAt(new Date());

                    agents.add(agent);
                }

                return agents;
            } else {
                log.error("========>Agent请求失败!");
            }

        } catch (Exception e) {
            log.error("AgentAPI调用失败: {}", e.getMessage());
            // 同步数据记录
            client.syncDataRecord(0, "Agent", "failed", "Agent Data", e.getMessage());
        }

        return null;
    }

}
